package com.example.demo.handle;

import com.example.demo.enums.ResultEnum;
import com.example.demo.exception.DemoException;
import com.example.demo.utils.ResultVOUtil;
import com.example.demo.vo.ResultVO;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by hongzhenyue on 17/8/15.
 * 集中处理异常
 */
@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    //    返回JSON格式
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVO handle(Exception e) {
        if (e instanceof DemoException) {
            DemoException demoException = (DemoException) e;
            return ResultVOUtil.failed(demoException.getCode(), demoException.getMessage());
        } else {
            logger.info("system error", e.getMessage());
//            return ResultVOUtil.failed(ResultEnum.ERROR.getCode(),ResultEnum.ERROR.getMsg());
            return ResultVOUtil.failed(ResultEnum.ERROR.getCode(), e.getMessage());
        }
    }
//    统一错误处理页面
//    @ExceptionHandler(value = Exception.class)
//    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
//        Map<String, Object> map=new HashedMap();
//        map.put("errorMsg", e.getMessage());
//        map.put("url", request.getRequestURL());
//        return new ModelAndView("common/error",map);
//    }
}
